<template>
  <div>
    <a-modal
      :visible="isShow"
      width="50%"
      style="min-width: 900px"
      ok-text="确认" cancel-text="取消" @cancel="cancelModal"
      :footer="null"
      class="ofc"
    >
      <a-spin tip="Loading..." :spinning="spinning">
        <div style="min-width: 900px">
          <h2 style="text-align: center;padding-top: 30px;">{{ title =='详情' ? '费用申请单' : title }}</h2>
          <div id="printContent" class="printContainer">
            <div
              style="width: 98%; padding-top: 30px;padding-left: 15px; height: 100%; padding-bottom: 20px"
            >
              <div style="padding-bottom: 10px" class="no-bord">
                编号：{{ obj.data.id }} <a style="cursor: pointer; text-decoration: underline; text-align: right; float: right; width: 240px;" @click="openDetail">项目序号：{{ obj.data.sortNo }}</a>
              </div>

              <a-row v-for="(i,index) in lable" :key="index">
                <a-col :span="c.field !='uploadFile' && c.border != 'left' ? 12 : 24" class="col" v-for="(c,ix) in i" :key="ix" :class="{'nor': ix %2 !==0, 'yor': c.border == 'left' }">
                  <div class="title">{{c.label}}</div>
                  <div class="val" v-if="c.component.indexOf('JDict') >-1 && c.componentProps && c.componentProps.dictCode">
                    <JDictTag class="xx" :isTag="false" :vals="setVal(c.field)" placeholder="--" :dictCode="c.componentProps.dictCode"/>
                  </div>
                  <div class="val" v-else>
                    <span v-if="c.field !='uploadFile'">{{ setVal(c.field) }}</span>
                    <span v-else style="display:flex; height: 54px;line-height: 1;width: 100%">
                      <span v-for="file in items.annexList" style="margin-top:8px; margin-right:12px">
                        <a :href="file.url" target="_blank">
                          <img src="../../../../assets//images/wallet.png" width="25" height="25" alt=""><br/>
                          <p :title="file.annexName" style="padding:0;margin:0;width:70px;" class="media-box__one">{{ file.annexName }}</p>
                        </a>
                      </span>
                    </span>
                  </div>
                </a-col>
              </a-row>
            </div>
            <div style="text-align: left;margin: 0 15px;padding-bottom: 30px">
              <a-row style="padding-bottom: 10px" v-if="dataSource.length">审核记录</a-row>
              <!-- 如果已经审核通过了，或者拒绝了不显示 -->
              <!-- <a-card v-if="items.applyStatus !=1 && items.applyStatus !=2"> -->
              <!-- 显示三次的审核意见，结果，时间，审核人 -->
              <!-- <a-card :bordered="false">  :scroll="{ y:230}"-->
              <a-table bordered :dataSource="dataSource" :columns="columns" :pagination="false" v-if="dataSource.length">
                <template #bodyCell="{ column, record }">
                  <template v-if="column.key === 'applyStatus'">
                    <div style="color:green;font-weight: 600;" v-if="record.applyStatus == 1" color="green">通过</div>
                    <div style="color:red;font-weight: 600;" v-if="record.applyStatus == 2" color="red">拒绝</div>
                    <div style="color:#108ee9;font-weight: 600;" v-if="record.applyStatus == 3" color="red">待审</div>
                    <div style="color:green;font-weight: 600;" v-if="record.applyStatus == 5" color="green">行政审核通过</div>
                    <div style="color:red;font-weight: 600;" v-if="record.applyStatus == 6" color="red">行政审核拒绝</div>
                  </template>
                </template>
              </a-table>
              <template v-if="title =='审核'">
                <a-row style="padding-bottom: 10px;margin-top:12px">成本计算器</a-row>
                <a-table style="width:100%" bordered :dataSource="budgeDataSource" :columns="budgeColumns" :pagination="false">
                  <!-- 当前预算状态 1 正常 显示一个绿色的圆圈  2 接近阈值 显示黄色圆圈  3 超出预算 显示红色圆圈 -->
                  <template #bodyCell="{ column, record }">
                      <template v-if="column.key === 'costStatus'">
                          <div style="color:green;font-weight: 600;" v-if="record.costStatus == 1" color="green">正常</div>
                          <div style="color:orange;font-weight: 600;" v-if="record.costStatus == 2" color="orange">接近阈值</div>
                          <div style="color:#ff0000;font-weight: 600;" v-if="record.costStatus == 3" color="red">{{ items.costType == 1 ? '预算使用率超出时间进度':'超出预算'}}</div>
                      </template>
                      <template v-if="column.key === 'costPercent'">
                        {{ record.costPercent * 100 }}
                      </template>
                  </template>
                </a-table>
              </template>
              <a-row style="padding-bottom: 10px;margin-top:12px" v-if="items.costType == 2">人员信息</a-row>
                <div style="margin-buttom: 20px" v-if="items.costType == 2">
                  <div class="hed">
                      <!-- <span style="flex: 0.2;">&nbsp;</span> -->
                      <span v-for="h in userColumns">{{ h.title }}</span>
                  </div>
                  <!-- {{ userData }} -->
                  <div class="cont">
                    <ul v-for="cont in userData">
                      <!-- <li style="flex: 0.2;">
                        <span>
                            <a-checkbox v-model:checked="cont.checked"></a-checkbox>
                        </span>
                      </li> -->
                      <li>
                          <span>{{ cont.name }}</span>
                          <!-- <JDictTag vals="staffId_dictTex" placeholder="--" dictCode="staffId"/> -->
                      </li>
                      <li>
                          <span>{{ cont.cost }}</span>
                      </li>
                      <li>
                          <span>{{ cont.startTime }}</span>
                      </li>
                      <li>
                        <span>{{ cont.endTime }}</span>
                      </li>
                      <li>
                        <span>{{ cont.usePercent * 100 }}%</span>
                      </li>
                      <li>
                        <span>{{ cont.content || '-' }}</span>
                      </li>
                      <li>
                        <a-tooltip placement="top" :title="cont.remark">
                          <span class="media-box__desc">{{ cont.remark || '-' }}</span>
                        </a-tooltip>
                      </li>
                  </ul>
                </div>
              </div>
              <!-- </a-card> -->
              <!-- <a-card :bordered="false"> -->
                <!-- 审核状态 1 通过 2 拒绝 3 待审 -->
                <template v-if="title =='审核'">
                  <a-row style="padding-bottom: 10px;margin-top:12px" v-if="items.applyStatus == 3 ||items.applyStatus == 5 ">审核</a-row>
                  <a-radio-group v-model:value="updata.applyStatus" name="radioGroup" v-if="items.applyStatus == 3 ||items.applyStatus == 5">
                    <a-radio value="1">通过</a-radio>
                    <a-radio value="2">拒绝</a-radio>
                  </a-radio-group>
                  <a-textarea v-model:value="updata.applyContent" placeholder="请输入说您的审核意见" allow-clear style="margin-top:12px" />
                  <a-button type="primary" style="margin-top:20px" @click="saveOrUpdateFun">提交审核</a-button>
                </template>
              <!-- </a-card> -->
            </div>
          </div>
          <div style="text-align: center;padding: 20px 0" v-if="title =='详情'"><a-button @click="print">打印文件</a-button></div>
        </div>
      </a-spin>
    </a-modal>
    <MonsterRocProjectSetupModal @register="registerModal" @success="handleSuccess"></MonsterRocProjectSetupModal>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from "vue"
import dayjs from "dayjs"
import printJS from 'print-js'
import { JDictTag } from '/@/components/Form'
import {useModal} from '/@/components/Modal'
import MonsterRocProjectSetupModal from '../components/MonsterRocProjectSetupModal.vue'
import { getLogInfo, getRcLog, submitDetail, tripInfo, hrInfo, otherInfo } from '../MonsterRocProjectSetup.api'
import { monsterSubmitApplys } from '../MonsterRocProjectSetup.api'
import { costApply, queryCurrentCostBudget, queryStaffBySubmitId } from '../MonsterSupplierCostSubmit.api'
import { getRocDetail } from '../MonsterRocProjectSetup.api'

import { dsfFormSchema, logColumns, budgeColumn, budgeDsfColumn, budgeHrColumn, budgeColumnOt, userColumn, officeColumns } from '../MonsterSupplierCostSubmit.data'
import { tripFormSchemas } from '../MonsterTripCostSubmit.data'
import { hrFormSchema } from '../MonsterHrCostSubmit.data'
import { otherFormSchema } from '../MonsterOtherCostSubmit.data'

import { USER_INFO_KEY } from '/@/enums/cacheEnum'
import { getAuthCache } from '/@/utils/auth'
const [registerModal, {openModal}] = useModal()

let user = getAuthCache(USER_INFO_KEY) || {}
let props = defineProps({
  isShow: false,
  ids: '',
  items: '',
  title: ''
})
const emit = defineEmits(['handleCallFun'])
const lable = ref([])
const obj = reactive({
  data: {}
})
const def = ref({})
const spinning = ref(true)

const updata = ref({
  submitId: props.items.submitId,
  applyStatus: "1",
  applyUserId: user.id,
  applyContent: '',
  costType: 1
  // submitId  applyStatus （审核状态 1 通过 2 拒绝 3 待审核）传3，submitProjectType，
})

const dataSource = ref([])

const columns = ref(logColumns)

const budgeDataSource = ref([])

const budgeColumns = ref([])

const userColumns = ref(userColumn)
const userData = ref([])

const cancelModal = () => {
  emit('handleCallFun')
}

function print() {

  printJS({
    // 要打印的html的节点id
    printable: "printContent",
    header: "付款申请",
    headerStyle: "text-align: center;font-size:16px;font-weight:500",
    // 打印类型 html
    type: "html",
    // 继承样式
    targetStyle: '*',
    targetStyles: '*',
    // scanStyles: false,
    documentTitle: " ",
    // 默认800，设置1000是因为我窗口宽度是1000，而导致页面靠近左边，设置1000就正常居中了。
    maxWidth: "1000"
  })
}

async function openDetail () {
  // topTitle.value = '详情'
  let record = await getRocDetail({id: obj.data.projectId})
  // 处理图片
  let img = []
  let file = record.annexList ? JSON.parse(JSON.stringify(record.annexList)) : []
  file.forEach((item) => {
    img.push({
      uid: item.id,
      fileName: item.annexName,
      filePath: item.url,
      status: 'done',
      response: {
        status: 'history',
        message: item.url
      }
    })
  })
  openModal(true, {
    record: Object.assign(record,{uploadFile:JSON.stringify(img)}),
    isUpdate: true,
    showFooter: false,
  });
}

function queryListFun (item, amount) {
  queryCurrentCostBudget({operateType:1, submitType:item.costType, projectId: item.projectId.toString(),id: item.id.toString(),payAmount:amount}).then(res => {
    let cost = (res.remainderBudget  - amount) / res.totalCost
    // if(cost < res.remindThreshold && cost < res.warningThreshold) {
    //   res.costStatus = 2
    // }
    // else if(cost < res.warningThreshold) {
    //   res.costStatus = 3
    // }
    // else {
    //   res.costStatus = 1
    // }
    res.payAmount = amount
    budgeDataSource.value = [res]
  })
}

function setVal(field) {
  for(let o in obj.data) {
    if(o == field && field && field !='pm' && field !='percent') {
      return obj.data[o] || '-'
    }
    if(field =='percent') {
      return (Number(obj.data['percent']) * 100) + '%' || '-'
    }

    if(field =='pm') {
      return obj.data['createBy'] || '-'
    }

  }
}

async function rocDetail () {
  let amount
  try{
    let d = await monsterSubmitApplys({ id: props.items.id})
    def.value = d
    let r
    let arr = []
    // 第三方
    if(props.items.costType == 1){
      r = await submitDetail({id: props.items.submitId})
      arr = JSON.parse(JSON.stringify(dsfFormSchema)).splice(0,dsfFormSchema.length - 1)
      amount = r.amount
    }
    // 人力
    if(props.items.costType == 2){
      r = await hrInfo({id: props.items.submitId})
      arr = JSON.parse(JSON.stringify(hrFormSchema)).splice(0,hrFormSchema.length - 1)
      amount = r.totalHrAmount

      let us = await queryStaffBySubmitId({submitId:props.items.submitId})
      userData.value = us
    }
    // 差旅
    if(props.items.costType == 3){
      r = await tripInfo({id: props.items.submitId})
      arr = JSON.parse(JSON.stringify(tripFormSchemas)).splice(0,tripFormSchemas.length - 1)
      amount = r.totalTripAmount
    }
    // 其他
    if(props.items.costType == 4){
      r = await otherInfo({id: props.items.submitId})
      arr = JSON.parse(JSON.stringify(otherFormSchema)).splice(0,otherFormSchema.length - 1)//otherFormSchema
      amount = r.totalAmount
    }

    // let r = await submitDetail({id: props.items.submitId})
    obj.data = r
    const result = []
    // let arr = formSchema.slice(0,formSchema.length - 1)
    for (let i = 0; i < arr.length; i += 2) {
      result.push(arr.slice(i, i + 2))
    }
    lable.value = result

    let l = await getLogInfo({ projectId: props.items.projectId, submitId: props.items.submitId })
    dataSource.value = l
    spinning.value = false
  }catch(er){
    spinning.value = false
  }
  queryListFun(props.items, amount)
}

function saveOrUpdateFun () {

  delete def.value.applyTimes
  costApply(Object.assign(def.value,{projectName:props.items.projectName,applyContent:updata.value.applyContent,applyUserId:user.id,applyTime: dayjs(new Date()).format('YYYY-MM-DD HH:mm:ss'),applyStatus:updata.value.applyStatus}), handleSuccess)
  // .then((res) => {
  //   emit('handleCallFun', true)
  // })
  // costApply(Object.assign(updata.value,{applyTime: dayjs(new Date()).format('YYYY-MM-DD HH:mm:ss')})).then((res) => {
  //   emit('handleCallFun', true)
  // })
}

// 成功后的回调
function handleSuccess () {
  emit('handleCallFun', true)
}

onMounted(() => {
  // 其他
  if(props.items.costType == 4) {
    budgeColumns.value = budgeColumnOt
  } else if(props.items.costType == 1) {
    budgeColumns.value = budgeDsfColumn
  } else if(props.items.costType == 2) {
    budgeColumns.value = budgeHrColumn
  } else if(props.items.costType == 3) {
    budgeColumns.value = officeColumns
  }

  else {
    budgeColumns.value = budgeColumn
  }
  rocDetail()
})
</script>
<style scoped lang="less">
/deep/ .el-dialog__footer {
  height: 70px;
  margin-top: 15px;
}

.col {
  // border: 1px solid #e6e9f0;
  border: 1px solid #666;
  border-top: 0;
  min-height: 55px;
  display: flex;
  align-items: center;

  div {
    padding-left: 20px;
  }
  .title {
    min-width: 140px;
    // min-width: 160px;
    // background-color: #f5f5f5; //title的背景色
    // color: #1F2E4D;
    color: #666;
  }
  .val {
    flex: 1;
    // border-left: 1px solid #e6e9f0;
    border-left: 1px solid #666;
    // color: #3D4966;
    color: #666;
    min-height: 55px;
    display: inline-flex;
    align-items: center;
    word-break:break-all;
    height: 100%;
    width: 100%;
    span, .xx{
      flex-shrink: 0;
      width: 100%;
    }
  }
}
.nor{
  border-left: 0;
}
.yor {
  border-left: 1px solid #666;
}
.no-bord{
  border-bottom: 1px solid #666;
}

.hed{
    display: flex;
    border: 1px solid #e5e7eb;
    background: #FAFAFA;
    border-bottom: 0;
    span{
        flex: 1;
        border-right: 1px solid #f0f0f0;
        padding: 12px 8px;
    }
}
.cont{
    border-bottom: 1px solid #e5e7eb;
    ul{
        display: flex;
        border: 1px solid #e5e7eb;
        margin: 0;
        border-bottom: 0;
    }
    li{
        flex: 1;
        border-right: 1px solid #f0f0f0;
        padding: 12px 8px;
    }
}
.media-box__desc {
    color: rgba(0,0,0,0.3);
    color: var(--weui-FG-2);
    font-size: 14px;
    line-height: 1.4;
    padding-top: 4px;
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 2;
    word-wrap: break-word;
    -webkit-hyphens: auto;
    hyphens: auto;
    padding-left: 0;
}
</style>


<style>
.printContainer {
  -webkit-print-color-adjust: exact;
}
@page { margin: 0; }
.ofc .xx{
  flex-shrink: 0;
  width: 100%;
}
</style>
